from db.userDBManager import UserDBManager
from .project import Project
from utils.randomUtils import generate_random_string
class User:
    def __init__(self, user_id, user_db_manager:UserDBManager):
        self.user_id = user_id  
        self.user_db_manager = user_db_manager 
        pro_raw = user_db_manager.get_user_projects(user_id)
        self.user_info = user_db_manager.get_user_login_info(user_id)
        self.editingProjects = pro_raw
        self.runningProjects = {}

    # 用户 将Project 加入到EditingProjects中
    def addEditingProject(self, project_id, content):
        self.editingProjects[project_id] = content
        return self.editingProjects[project_id]

    def stopProject(self,project_id):
        if (project_id not in self.runningProjects): return
        pro = self.runningProjects[project_id]
        pro.stop()

    def deployProject(self, project_id,project_name, content):
        project =  ProjectManager.instance.addProject(generate_random_string(self.user_id, project_id), project_id, project_name, self)
        project.deployProject(content)
        self.runningProjects[project_id] = project

    def getEditingProject(self, project_id)->Project:
        if project_id not in self.editingProjects: 
            return None
        return self.editingProjects.get(project_id)
    
    def getEditingProjects(self)->list[Project]:
        return list(self.editingProjects.values())
    
    def saveUserProject(self, projectID, projectContent)->bool:
        self.editingProjects[projectID] = projectContent
        pros = self.user_db_manager.get_user_projects(self.user_id)
        pros[projectID] = projectContent
        self.user_db_manager.save_user_projects(self.user_id, pros)
        return True

    def getEditingProjects(self):
        return self.editingProjects
    def getRunningProjects(self):
        return self.runningProjects

class UserManager:
    def __init__(self, user_db_manager: UserDBManager):
        self.users = {}
        self.users_db_manager = user_db_manager

    def addUser(self, user_id):
        self.users[user_id] = User(user_id, self.users_db_manager)
        return self.users[user_id]

    def getUser(self, user_id)->User:
        if user_id not in self.users: 
            return None
        return self.users.get(user_id)
    
    


class ProjectManager:
    instance = None
    app = None
    def __init__(self, app):
        self.randomKeyToProject = {}
        ProjectManager.instance = self
        ProjectManager.app = app

    def addProject(self, random_key, project_id, project_name, user:User):
        self.randomKeyToProject[random_key] = Project(project_id, random_key, project_name, user)
        return self.randomKeyToProject[random_key]

